package geektime.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.*;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * nio的多路复用演示
 * 使用多个线程来对应处理不同的客户端
 */
public class MultiThreadReactor {

    private static ExecutorService threadPool = Executors.newFixedThreadPool(100);

    public static void main(String[] args) {
        try {
            // 创建selector和serverSocketChannel
            Selector selector = Selector.open();
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            // serverSocketChannel绑定端口
            serverSocketChannel.bind(new InetSocketAddress(1234));
            // 将serverSocketChannel设置为非阻塞
            serverSocketChannel.configureBlocking(false);
            // 将serverSocketChannel注册到selector中，并说明其关注点为连接请求
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            while (true) {
                // 如果没有准备好的channel，则让循环continue
                if (selector.selectNow() < 0) {
                    continue;
                }
                // 获取selector的selected-sets
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();
                    if (selectionKey.isAcceptable()) {
//                        ServerSocketChannel serverChannel = (ServerSocketChannel)selectionKey.channel();
                        SocketChannel channel = serverSocketChannel.accept();
                        // 将channel设置为非阻塞
                        channel.configureBlocking(false);
                        // 将channel注册到selector，并说明其关注点为read操作
                        channel.register(selector, SelectionKey.OP_READ);
                        System.out.println("MultiThreadReactor accept message from: " + channel.socket().getInetAddress().toString() + "/" + channel.socket().getPort());
                    } else if(selectionKey.isValid() && selectionKey.isReadable()){
                        threadPool.submit(new RequestHandleProcessor(selectionKey));
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
